package com.spx.core.handlers;

import java.sql.Timestamp;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;

import com.spx.core.CoreActivator;
import com.spx.core.types.User;
import com.spx.kernel.Application;
import com.spx.kernel.types.ModelUtil;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * 
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class UserViewPasteHandler extends AbstractHandler
{
	/**
	 * The constructor.
	 */
	public UserViewPasteHandler()
	{
	}

	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException
	{

		final Shell shell = HandlerUtil.getActiveShell(event);
		for (final Object object : Application.getClipboard())
		{
			if (object instanceof User)
			{
				final User user = (User) object;
				User newUser = new User();

				newUser = ModelUtil.duplicate(user);

				final InputDialog dialog = new InputDialog(shell, "", "Enter New Name", newUser.getName(), new NameValidator());
				dialog.open();
				newUser.setName(dialog.getValue());
				CoreActivator.getDefault().getSecurityService().addUser(newUser);
			}

		}

		return null;
	}

}

class NameValidator implements IInputValidator
{
	Timestamp lastCheck;
	private boolean fault;

	/**
	 * Validates the String. Returns null for no error, or an error message
	 * 
	 * @param newText
	 *            the String to validate
	 * @return String
	 */

	public String isValid(String newText)
	{
		final int len = newText.length();
		//
		final Timestamp ts = new Timestamp(System.currentTimeMillis() - 1000);
		if (lastCheck.before(ts))
		{
			if (CoreActivator.getDefault().getSecurityService().findUser(newText) != null)
			{
				fault = true;

			} else
			{
				fault = false;
			}
		}
		if (fault)
		{
			return "User exists";
		}
		// Determine if input is too short or too long
		if (len < 2)
		{
			return "Too short";
		}
		if (len > 48)
		{
			return "Too long";
		}

		// Input must be OK
		return null;
	}

	public NameValidator()
	{
		lastCheck = new Timestamp(System.currentTimeMillis());
	}
}
